Note: This tutorial assumes that you have completed the previous tutorials: Understanding Service Types, Service Discovery via Polling. |
![]() |
Service Discovery via Callbacks
Description: Shows how to do service discovery with jmdns using callbacks.Keywords: zeroconf jmdns
Tutorial Level: INTERMEDIATE
Contents
Notes
This is mostly working now - particularly for android systems however this part of the jmmdns code is still fairly experimental and will be likely to change. If you run into issues, please contact <d DOT stonier AT gmail DOT com>, we're working the jmdns developer to improve certain parts of the discovery mechanisms.
Code Sample
1 import java.util.ArrayList;
2 import com.github.ros_java.zeroconf_jmdns_suite.jmdns.Zeroconf;
3 import com.github.ros_java.zeroconf_jmdns_suite.jmdns.DiscoveredService;
4 import com.github.ros_java.zeroconf_jmdns_suite.jmdns.ZeroconfDiscoveryHandler;
5 import com.github.ros_java.zeroconf_jmdns_suite.jmdns.DiscoveredService;
6
7 class DiscoveryHandler implements ZeroconfDiscoveryHandler {
8 public DiscoveryHandler() {
9 this.discovered_services = new ArrayList<DiscoveredService>();
10 }
11 public void serviceAdded(DiscoveredService service) {
12 // custom handling code
13 }
14
15 public void serviceRemoved(DiscoveredService service) {
16 // custom handling code
17 }
18
19 public void serviceResolved(DiscoveredService service) {
20 // custom handling code
21 }
22 private ArrayList<DiscoveredService> discovered_services;
23 }
24
25 Zeroconf discovery = new Zeroconf();
26 DiscoveryHandler discovery_handler = new DiscoveryHandler();
27 zeroconf.setDefaultDiscoveryCallback(discovery_handler);
28 discovery.addListener("_ros-master._tcp","local");
Breaking it Down
Initialise the module:
1 Zeroconf discovery = new Zeroconf();
2 discovery.addListener("_ros-master._tcp","local");
Add a default discovery handler (written by yourself) (see further down for an example). This will be used to handle callbacks for every listener you add.
1 DiscoveryHandler discovery_handler = new DiscoveryHandler();
2 zeroconf.setDefaultDiscoveryCallback(discovery_handler);
3 discovery.addListener("_ros-master._tcp","local");
Alternatively, you can add specific handlers for specific listeners:
1 TCPDiscoveryHandler tcp_discovery_handler = new TCPMasterDiscoveryHandler();
2 discovery.addListener("_ros-master._tcp","local",tcp_discovery_handler);
3 UDPDiscoveryHandler udp_discovery_handler = new UDPMasterDiscoveryHandler();
4 discovery.addListener("_ros-master._udp","local",udp_discovery_handler);
Example
Example code can be found in the jmdns tutorials and also in indigo implementation of the android ros master browser.